import React, { useState, useEffect } from "react";
import logo from "./assets/images/logo.svg";
import styles from "./App.module.css";
import Robot from "./components/Robot";
import RobotDiscount from "./components/RobotDiscount";
import ShoppingCart from "./components/ShoppingCart";

interface Props {
  // username: string;
}

const App: React.FC<Props> = (props) => {
  const [robotGallery, setRobotGallery] = useState<any>([]);
  const [loading, setLoading] = useState<Boolean>(false);
  const [error, setError] = useState<string>();
  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        const responses = await fetch(
          "https://jsonplaceholder.typicode.com/users"
        );
        const data = await responses.json();
        setRobotGallery(data);
      } catch (error) {
        setError(error);
      }
      setLoading(false);
    };
    fetchData();
  }, []);
  return (
    <div className={styles.app}>
      <div className={styles.appHeader}>
        <img src={logo} className={styles.appLogo} alt="logo" />
        <h1>罗伯特机器人购物平台</h1>
      </div>
      <ShoppingCart />
      {!error || (error !== "" && <div>网站出错了：{error}</div>)}
      {!loading ? (
        <div className={styles.robotList}>
          {robotGallery.map((r: any, index: any) =>
            index % 2 === 0 ? (
              <RobotDiscount key={r.id} id={r.id} email={r.email} name={r.name} />
            ) : (
              <Robot key={r.id} id={r.id} email={r.email} name={r.name} />
            )
          )}
        </div>
      ) : (
        <h2>loading.....</h2>
      )}
    </div>
  );
};

export default App;
